package red.yancloud.www.ui.activity

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_repository_entry_list.*
import kotlinx.android.synthetic.main.activity_repository_entry_list.errorView
import kotlinx.android.synthetic.main.activity_repository_entry_list.smartRefreshLayout
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.RepositoryFirstLevelData
import red.yancloud.www.internet.bean.RepositorySort
import red.yancloud.www.internet.bean.TypeData
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.ui.adapter.TypeRecyclerAdapter
import red.yancloud.www.ui.adapter.RepositoryEntryListRecyclerAdapter
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.TimeFormatUtil
import red.yancloud.www.util.ToastUtils
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/19 18:22
 * E_Mail：yh131412hys@163.com
 * Describe：知库词条
 * Change：
 * @Version：V1.0
 */
class RepositoryEntryListActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "RepositoryEntryListActi"

    private var page: Int = 1
    private var limit: String = "10"

    private var selectPosition = -1//用于记录用户选择的变量
    private var typeId:String = ""
    private lateinit var mTypeAdapter:TypeRecyclerAdapter
    private lateinit var typeList:ArrayList<TypeData>

    private lateinit var repositoryEntryListAdapter:RepositoryEntryListRecyclerAdapter

    override val layoutId: Int
        get() = R.layout.activity_repository_entry_list

    override fun initData() {

 //        一级分类cid
        val cid = intent.getIntExtra("cid", -1)
//        二级分类id
        val id = intent.getStringExtra("id")
        val childrenTypeList = intent.getParcelableArrayListExtra<RepositorySort.DataBean.ChildrenBean>("SortChildrenBean")
        typeList = ArrayList()
//        typeList.add(TypeData("全部",cid.toString()))
        for (childrenBean in childrenTypeList) {

            typeList.add(TypeData(childrenBean.name,childrenBean.id.toString()))
        }
//        typeId默认值
        typeId = typeList[0].typeId

        initRecyclerView()
        initSmartRefreshLayout()

        Log.d(TAG,"$cid-------$id-------$typeList")

//                    取消全部
//        getZhiKuFirstLevelData(cid.toString())
        getZhiKuSecondLevelData(typeId)
    }

    override fun configViews() {

        title_tv.text=intent.getStringExtra("title")
        back_iv.setOnClickListener(this)
    }

    private fun initRecyclerView() {

//       Observable.create(object :ObservableOnSubscribe<List<TypeData>>{
//           override fun subscribe(emitter: ObservableEmitter<List<TypeData>>) {
//
//               val get = Jsoup.connect("http://zhi.yancloud.red/").get()
//               val select = get.select("[class=nav-content-box]>li")
//               for (element in select) {
//
//                   val text = element.select("span").select("a").text()
//                   typeList.add(TypeData(text,""))
////                   Log.d(TAG,text+element.select("ul").select("li").select("a").text())
//               }
//
//               emitter.onNext(typeList)
//           }
//
//       }).subscribeOn(Schedulers.io())
//           .unsubscribeOn(Schedulers.io())
//           .observeOn(AndroidSchedulers.mainThread())
//           .subscribe(object :io.reactivex.functions.Consumer<List<TypeData>>{
//               override fun accept(t: List<TypeData>?) {
//
//                   typeAdapter.addData(typeList)
//               }
//           })

        repositoryEntryListActivity_type_rV.layoutManager= LinearLayoutManager(mContext, RecyclerView.HORIZONTAL,false)
        mTypeAdapter = TypeRecyclerAdapter(R.layout.item_read_type_list)
        repositoryEntryListActivity_type_rV.adapter= mTypeAdapter
        mTypeAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                //获取选中的参数
                selectPosition = position
                mTypeAdapter.setSelectPosition(selectPosition)
                mTypeAdapter.notifyDataSetChanged()

                page=1
                typeId = (adapter!!.data[position] as TypeData).typeId
                if (intent.getIntExtra("cid", -1)==typeId.toInt()) {

                    getZhiKuFirstLevelData(typeId)
                }else{

                    getZhiKuSecondLevelData(typeId)
                }
            }
        }
        mTypeAdapter.addData(typeList)

        repositoryEntryListActivity_rV.layoutManager=LinearLayoutManager(mContext,RecyclerView.VERTICAL,false)
//        repositoryEntryListActivity_rV.addItemDecoration(RecycleViewDivider(mContext, ScreenUtils.dip2px(mContext,10f)))
        repositoryEntryListActivity_rV.addItemDecoration(RecycleViewDivider(
                this,
                DividerItemDecoration.VERTICAL,
                ScreenUtils.dpToPx(10f).toInt(),
                R.color.color_f5
            )
        )
        repositoryEntryListAdapter = RepositoryEntryListRecyclerAdapter()
        repositoryEntryListActivity_rV.adapter= repositoryEntryListAdapter
        repositoryEntryListAdapter.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

//                http://www.yancloud.red/Yancloudapp/News/entry/id/
                startActivity(
                    Intent(mContext, NewsInfoActivity::class.java)
                        .putExtra(
                            "url",
                            "${Constants.API_BASE_RED_CLOUD_URL}News/entry/?id=${repositoryEntryListAdapter.mData[position].id}")
                        .putExtra("model",Constants.CollectModel.ZHIKU)
                        .putExtra("id",repositoryEntryListAdapter.mData[position].id.toString())
                )
            }
        })
    }

    private fun initSmartRefreshLayout() {

        val mClassicsHeader = smartRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

//        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
        smartRefreshLayout.setOnRefreshListener(OnRefreshListener {

            if (!NetworkUtils.isConnected(this)) {
                errorView.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }
            page=1
            if (intent.getIntExtra("cid", -1)==typeId.toInt()) {

                getZhiKuFirstLevelData(typeId)
            }else{

                getZhiKuSecondLevelData(typeId)
            }
        })
        smartRefreshLayout.setOnLoadMoreListener(OnLoadMoreListener { refreshLayout ->

            if (!NetworkUtils.isConnected(this)) {
                errorView.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishLoadMore()
                return@OnLoadMoreListener
            }
            page++
            if (intent.getIntExtra("cid", -1)==typeId.toInt()) {

                getZhiKuFirstLevelData(typeId)
            }else{

                getZhiKuSecondLevelData(typeId)
            }
        })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv -> finish()
            else -> {
            }
        }
    }

    private fun getZhiKuFirstLevelData(cid: String) {

        loadingDialog.show()

        RedCloudApis.getInstance().getZhiKuFirstLevelData(page.toString(), limit,cid,object : Observer<RepositoryFirstLevelData> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: RepositoryFirstLevelData) {

                if (t.code == Constants.SYSTEM_OK) {
                    if(t.data != null&& t.data.size > 0){

//                            totalPage = t.data.page.totalPage
                        errorView.visibility=View.GONE
                        smartRefreshLayout.visibility=View.VISIBLE
                        if (page==1) {

                            repositoryEntryListActivity_rV.scrollToPosition(0)
                            repositoryEntryListAdapter.clear()
                            repositoryEntryListAdapter.addData(t.data)
                            smartRefreshLayout.resetNoMoreData()
                            smartRefreshLayout.finishRefresh()
                        }else {

                            repositoryEntryListAdapter.addData(t.data)
                            smartRefreshLayout.finishLoadMore()
                        }
                    }else{

                        if (page==1){

                            smartRefreshLayout.finishRefresh()

                            errorView.visibility=View.VISIBLE
                            smartRefreshLayout.visibility=View.GONE
                        }else{

                            ToastUtils.showToast(getString(R.string.data_all_load))
                            smartRefreshLayout.finishLoadMore()
                        }
                    }
                }else{

                    if (page==1) {

                        errorView.visibility=View.VISIBLE
                        smartRefreshLayout.visibility=View.GONE
                    }else{

                        smartRefreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
                        ToastUtils.showToast(getString(R.string.data_all_load))
                    }
                }

                loadingDialog.dismiss()
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
            }
        })
    }

    private fun getZhiKuSecondLevelData(id: String) {

        loadingDialog.show()

        RedCloudApis.getInstance().getZhiKuSecondLevelData(page.toString(),limit, id,object : Observer<RepositoryFirstLevelData> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: RepositoryFirstLevelData) {

                if (t.code == Constants.SYSTEM_OK) {
                    if(t.data != null&& t.data.size > 0){

//                            totalPage = t.data.page.totalPage
                        errorView.visibility=View.GONE
                        smartRefreshLayout.visibility=View.VISIBLE
                        if (page==1) {

                            repositoryEntryListActivity_rV.scrollToPosition(0)
                            repositoryEntryListAdapter.clear()
                            repositoryEntryListAdapter.addData(t.data)
                            smartRefreshLayout.resetNoMoreData()
                            smartRefreshLayout.finishRefresh()
                        }else {

                            repositoryEntryListAdapter.addData(t.data)
                            smartRefreshLayout.finishLoadMore()
                        }
                    }else{

                        if (page==1){

                            smartRefreshLayout.finishRefresh()

                            errorView.visibility=View.VISIBLE
                            smartRefreshLayout.visibility=View.GONE
                        }else{

                            ToastUtils.showToast(getString(R.string.data_all_load))
                            smartRefreshLayout.finishLoadMore()
                        }
                    }
                }else{

                    if (page==1) {

                        errorView.visibility=View.VISIBLE
                        smartRefreshLayout.visibility=View.GONE
                    }else{

                        smartRefreshLayout.finishLoadMoreWithNoMoreData()//将不会再次触发加载更多事件
                        ToastUtils.showToast(getString(R.string.data_all_load))
                    }
                }

                loadingDialog.dismiss()
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
            }
        })
    }
}
